<?php
/**
 * Copyright (c) 2020
 * 摘    要：
 * 作    者：san
 * 修改日期：2020.05.11
 */

namespace App\Library\Email;

use App\Library\Clog\Log;
use ErrorException;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

class CEmail
{
    /**
     * @var PHPMailer $mail
     */
    protected $mail;

    public function __construct()
    {
        $this->mail = new PHPMailer(true);

        //服务器配置
        $this->mail->CharSet   = "UTF-8";
        $this->mail->SMTPDebug = 0;
        $this->mail->isSMTP();
        $this->mail->Host       = env('AUTODS_MAIL_HOST');
        $this->mail->SMTPAuth   = true;
        $this->mail->Username   = env('AUTODS_MAIL_USER', '');
        $this->mail->Password   = env('AUTODS_MAIL_PASS', '');
        $this->mail->SMTPSecure = env('AUTODS_MAIL_ENCRYPTION', 'ssl');
        $this->mail->Port       = env('AUTODS_MAIL_PORT', 465);
    }

    /**
     * 模板
     *
     * @param string $tpl
     * @param array $compact
     * @throws ErrorException
     * @return CEmail
     */
    public function compose(string $tpl, array $compact)
    {
        $mailTpl = __DIR__ . '/tpl/' . $tpl . '.html';

        if (!file_exists($mailTpl)) {
            throw new ErrorException("邮件模板不存在");
        }

        $content = file_get_contents($mailTpl);
        if ($compact) {
            foreach ($compact as $key => $item) {
                $content = str_replace('${' . $key . '}', $item, $content);
            }
        }

        $this->mail->Body = $content;
        $this->mail->isHTML(true);

        return $this;
    }

    /**
     * 发件人
     *
     * @throws Exception
     * @return CEmail
     */
    public function setFrom()
    {
        $this->mail->setFrom(env('AUTODS_MAIL_FROM', ''), env('AUTODS_MAIL_FROM_NAME'));

        return $this;
    }

    /**
     * 收件人
     *
     * @param $to
     * @throws Exception
     * @return CEmail
     */
    public function setTo($to)
    {
        $this->mail->addAddress($to);

        return $this;
    }

    /**
     * 抄送
     *
     * @param $cc
     * @throws Exception
     * @return CEmail
     */
    public function setCc($cc)
    {
        if ($cc) {
            $this->mail->addCC($cc);
        }

        return $this;
    }

    /**
     *
     * @param $subject
     * @return CEmail
     */
    public function setSubject($subject)
    {
        $this->mail->Subject = $subject;

        return $this;
    }

    /**
     * 设置附件
     *
     * @param $attachment
     * @throws Exception
     * @return CEmail
     */
    public function setAttachment($attachment)
    {
        $this->mail->addAttachment($attachment);

        return $this;
    }

    /**
     * 发送邮件
     *
     * @throws Exception
     */
    public function send()
    {
        return $this->mail->send();
    }
}
